<template>
  <div class="p-6">
    <h1 class="text-2xl font-bold mb-4">用户管理</h1>
    <UserForm
      :user="editingUser"
      @submit="handleUserSubmit"
      @reset="handleUserReset"
    />
    <h2 class="text-xl font-semibold mb-2">用户列表</h2>
    <UserTable
      :users="users"
      :currentPage="currentPage"
      :pageSize="pageSize"
      :totalUsers="totalUsers"
      @edit="handleEditUser"
      @delete="handleDeleteUser"
      @page-change="handlePageChange"
    />
  </div>
</template>

<script>
import axios from 'axios';
import UserForm from './forms/UserForm.vue';
import UserTable from './forms/UserTable.vue';

export default {
  components: {
    UserForm,
    UserTable,
  },
  data() {
    return {
      users: [],
      currentPage: 1,
      pageSize: 10,
      totalUsers: 0,
      editingUser: null, // 当前正在编辑的用户对象
    };
  },
  methods: {
    async getUsers() {
      try {
        const response = await axios.get('/api/users', {
          params: {
            page: this.currentPage,
            pageSize: this.pageSize,
          },
        });
        this.users = response.data.users; // 假设返回的数据结构为 { users: [], total: 0 }
        this.totalUsers = response.data.total; // 获取总用户数
      } catch (error) {
        console.error('获取用户失败:', error);
      }
    },
    handleUserSubmit(form) {
      if (this.editingUser) {
        this.updateUser(this.editingUser.id, form);
      } else {
        this.createUser(form);
      }
    },
    handleUserReset() {
      this.editingUser = null;
    },
    async createUser(form) {
      try {
        await axios.post('/api/users', form);
        this.getUsers(); // 刷新用户列表
      } catch (error) {
        console.error('创建用户失败:', error);
      }
    },
    async updateUser(id, form) {
      try {
        await axios.patch(`/api/users/${id}`, form);
        this.getUsers(); // 刷新用户列表
        this.editingUser = null; // 编辑完成后重置编辑用户对象
      } catch (error) {
        console.error('更新用户失败:', error);
      }
    },
    async deleteUser(id) {
      try {
        await axios.delete(`/api/users/${id}`);
        this.getUsers(); // 刷新用户列表
      } catch (error) {
        console.error('删除用户失败:', error);
      }
    },
    handleEditUser(user) {
      this.editingUser = { ...user }; // 预填充表单
    },
    handleDeleteUser(id) {
      this.deleteUser(id);
    },
    handlePageChange(page) {
      this.currentPage = page;
      this.getUsers();
    },
  },
  mounted() {
    this.getUsers();
  },
};
</script>

<style scoped>
/* 样式代码 */
</style>